from backend.database.base_db import BaseDB
from backend.database.base_db import BaseDB
from backend.models.food import Food

class FoodDB(BaseDB):
    def __init__(self):
        super().__init__('food')
    
    def get_food_by_id(self, food_id):
        query = "SELECT * FROM food WHERE food_id = %s"
        result = self.fetch_one(query, (food_id,))
        return Food.from_dict(result) if result else None
    
    def get_all_foods(self):
        query = "SELECT * FROM food"
        results = self.fetch_all(query)
        return [Food.from_dict(result) for result in results]
    
    def search_foods(self, keyword):
        query = "SELECT * FROM food WHERE food_name LIKE %s OR description LIKE %s"
        search_param = f"%{keyword}%"
        results = self.fetch_all(query, (search_param, search_param))
        return [Food.from_dict(result) for result in results]
    
    def get_available_foods(self):
        query = "SELECT * FROM food WHERE stock > 0"
        results = self.fetch_all(query)
        return [Food.from_dict(result) for result in results]
    
    def add_food(self, food):
        data = food.to_dict()
        # 移除可能存在的None值
        data = {k: v for k, v in data.items() if v is not None}
        # 如果有food_id，也移除，让数据库自动生成
        if 'food_id' in data:
            del data['food_id']
        
        # 如果图片路径为空，使用默认路径
        if 'image_path' not in data or data['image_path'] is None:
            data['image_path'] = "images/default_food.jpg"
        
        return self.insert(data)
    
    def update_food(self, food):
        data = food.to_dict()
        food_id = data.pop('food_id', None)
        if food_id is None:
            raise ValueError("菜品ID不能为空")
        
        # 移除可能存在的None值
        data = {k: v for k, v in data.items() if v is not None}
        
        return self.update(data, f"food_id = {food_id}")
    
    def delete_food(self, food_id):
        return self.delete(f"food_id = {food_id}")
    
    def update_stock(self, food_id, quantity):
        query = "UPDATE food SET stock = stock - %s WHERE food_id = %s AND stock >= %s"
        cursor = self.execute_query(query, (quantity, food_id, quantity))
        affected_rows = cursor.rowcount
        cursor.close()
        return affected_rows > 0